import orderService, {orderStatus, payTypeOptions} from "../../../service/order";
import siteService, {getSite} from "../../../service/site";
import {showModel, showToast} from "../../../utils/tool";
import {emit} from "../../../utils/event";

const app = getApp()
const global = app.globalData

Page({
    data: {
        nav:{
            title:"订单详情"
        },
        loading:false,
        info:null,
        imageUrl: global.imageUrl,
        site:null,
        payTypeOptions:payTypeOptions,
        orderStatus:orderStatus,
        btnLoading:false,
    },
    onLoad: function (options={}) {
        this.setData({
            options,
        })
    },
    onShow() {
        const {options} = this.data
        this.init(options)
    },

    /**
     * 文本复制
     * @param e
     */
    copyText (e) {
        const {copy} = e.currentTarget.dataset;
        wx.setClipboardData({
            data: copy,
        })
    },

    kefuClick(){
      siteService.showKefu(this.data.site)
    },

    payClick(){
        this.setData({
            btnLoading:true,
        })
        const {info, options} = this.data
        // 调起支付
        orderService.payment(info).then(r => {
            showToast("付款成功")
            this.setData({
                btnLoading:false
            })
            // 更新订单状态
            this.init(options)
        })
    },

    cancelClick(){
        const {info, options} = this.data
        orderService.cancel(info.id).then(r => {
            showToast("取消成功")
            this.init(options)
        })
    },

    /**
     * 确认收货
     */
    receiveHandle(e){
        const {itemIndex} = e.currentTarget.dataset
        const {info} = this.data
        showModel("确认收到商品了吗",{
            confirm:() => {
                orderService.receive(info.id).then(r => {
                    // 将状态改为待评论
                    this.setData({
                        [`info.order_status`]:'reply'
                    })
                })
            }
        })
    },
    replyClick(e){
        const {info} = this.data

        wx.navigateTo({
            url:`/pages/user/order/reply_edit?order_id=${info.id}`,
            events:{
                // 添加评论的监听器
                addReplyEvent:() => {
                    this.setData({
                        [`info.order_status`]:'done'
                    })
                }
            }
        })

    },

    // 申请退款
    refundClick(){
        const {info} = this.data
        wx.navigateTo({
            url:`/pages/user/order/refund_apply?order_id=${info.id}`,
            success:(res) => {
                // 通过eventChannel向被打开页面传递订单信息
                res.eventChannel.emit("fromOrderShowEvent", { order: info })
            }
        })
    },


    async init(options){
        const info = await orderService.find(options.id)
        const site = await getSite();
        this.setData({
            site,
            options,
            info,
            loading:false,
        })
    }
});
